import { Service } from 'egg';
import { User } from '../model/User';

class CloundService extends Service {
    /**
     * 获取聊天好友列表
     * @param param 
     */
    public async getCloundFriend(param: any) {
        const user_id = param.user_id;
        const queryStr = `
                SELECT
                    toUserId AS user_id,
                    created_at  
                FROM
                    (
                SELECT
                    temp.toUserId,
                    MAX( temp.created_at ) AS created_at 
                FROM
                    (
                SELECT
                    toUserId,
                    MAX(created_at) created_at
                FROM
                    t_clound_message
                WHERE
                    fromUserId = :user_id 
                GROUP BY
                    toUserId UNION
                SELECT
                    fromUserId,
                    MAX(created_at) created_at
                FROM
                    t_clound_message 
                WHERE
                    toUserId = :user_id 
                GROUP BY
                    fromUserId 
                    ) temp 
                GROUP BY
                    toUserId 
                    ) temp 
                ORDER BY
                    created_at DESC`;
        const result = await this.ctx.model.query(queryStr, {
            type: this.ctx.model.QueryTypes.SELECT,
            replacements: { user_id }
        })
        const returnData: any = [];
        for (let i = 0; i < result.length; i++) {
            const target_user_id = result[i].user_id;
            const submitData = { user_id, target_user_id };
            const relation: any = await this.ctx.service.userService.checkRelation(submitData);
            const status = relation.status;
            const is_be_defiend = relation.is_be_defiend;
            if (status == 3 || is_be_defiend == 1) {
                continue;
            }
            const queryStr = `
                    SELECT
                        u.user_nickname,
                        u.user_avatarUrl 
                    FROM
                        t_user u
                        INNER JOIN t_school s ON u.user_school_id = s.school_id 
                        AND s.school_status = '1' 
                        AND u.user_id = :user_id
                        INNER JOIN t_college c ON u.user_college_id = c.college_id 
                        AND c.college_status = '1' 
                    WHERE
                        u.user_status <> '1' 
                        AND u.user_auditing_status <>3`;
            const cloundFriend: any = await this.ctx.model.query(queryStr, {
                type: this.ctx.model.QueryTypes.SELECT,
                replacements: { user_id: target_user_id }
            })
            if (cloundFriend.length <= 0) {
                continue;
            }
            const item: any = {};
            item.user_id = target_user_id;
            item.user_nickname = cloundFriend[0].user_nickname;
            item.user_avatarUrl = cloundFriend[0].user_avatarUrl;
            item.created_at = result[i].created_at;
            returnData.push(item);
        }
        return returnData;
    }

    /**
     * 获取当前用户与目标用户的聊天记录（按时间先后顺序排）
     * @param param 
     */
    public async getChatLog(param: any) {
        const user_id = param.user_id;
        const target_user_id = param.target_user_id;
        const page = Number(param.page);
        const size = Number(param.size);
        const offset = (page - 1) * size;
        const queryStr = `
                SELECT
                    * 
                FROM
                    (
                    (
                SELECT
                    c1.clound_message_id,
                    c1.content,
                    c1.fromUserId,
                    c1.toUserId,
                    c1.created_at,
                    c1.fromUserId = :user_id is_my
                FROM
                    t_clound_message c1 
                WHERE
                    c1.fromUserId = :target_user_id 
                    AND c1.toUserId = :user_id 
                    ) UNION
                    (
                SELECT
                    c1.clound_message_id,
                    c1.content,
                    c1.fromUserId,
                    c1.toUserId,
                    c1.created_at,
                    c1.fromUserId = :user_id is_my
                FROM
                    t_clound_message c1 
                WHERE
                    c1.fromUserId = :user_id 
                    AND c1.toUserId = :target_user_id
                    ) 
                    ) temp WHERE temp.created_at<:dateTime
                ORDER BY
                    temp.created_at DESC LIMIT ${offset},${size}`;
        const result = await this.ctx.model.query(queryStr, {
            type: this.ctx.model.QueryTypes.SELECT,
            replacements: { user_id, target_user_id, dateTime: param.dateTime }
        });
        if (result.length <= 0) {
            throw new Error(JSON.stringify({ code: 2, msg: '没有数据' }));
        }
        for (let i = 0; i < result.length; i++) {
            const user_id = result[i].fromUserId;
            const resultUser: any = await this.ctx.model.User.findOne<User>({ attributes: ['user_nickname', 'user_avatarUrl'], where: { user_id } });
            result[i].fromUserNickName = resultUser.user_nickname;
            result[i].fromUserAvatarUrl = resultUser.user_avatarUrl;
        }
        return result;
    }

    /**
     * 获取融云key
     */
    public async getCloundKey() {
        const key = this.app.config.rongyun.appKey;
        return { appKey: key };
    }
}
export default CloundService;